# Anova.auk 
# Tim Menzies
# Sept 12, 2012

"""
Synopsis
========

    @include "anova.auk"

"""

@include "lib.awk"
@include "fvalues.awk"

function ftest(rx,   \
               a,x,i,ns,n,s,mu,n0,s0,mu0,delta,\
               within_sos,between_sos,within_dof,\
               between_dof,msb,msw,f,critical) {
  # returns true if there is a difference
  a = length(rx)
  for(x in rx) 
    for(i in rx[x]) {
      n[x]++  ; s[x] += rx[x][i] ; mu[x] = s[x]/n[x]
      n0++    ; s0   += rx[x][i]  }
  for(x in rx) {
    mu0 += mu[x]/a;  
    ns += length(rx[x])/a
    for(i in rx[x])  {  
      delta= (rx[x][i] - round(mu[x]))
      within_sos += delta^2 }}
  for(x in rx)
    between_sos += ns*(mu[x] - mu0)^2
  between_dof = a - 1   
  within_dof  = a*(ns-1)
  msb         = between_sos / between_dof
  msw         = within_sos  / within_dof
  critical    = fcritical(between_dof,within_dof)
  f = msb/msw
  return f > critical
}
function fcritical(df1,df2,    row,col) {
  row = fnearest(df2,FVALS)
  col = fnearest(df1,FVALS[row])
  return FVALS[row][col]
}
function fnearest(df,f,  i,d,min,out) {
  min = 10**32
  for(i in f) {
    d = abs(i - df)
    if (d < min) {out = i; min= d}}
  return out
}

